package com.glsc.ngateway.common.api.common.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 解析json入参工具类
 */
public class JsonTool {

    private static Logger logger = LoggerFactory.getLogger(JsonTool.class);

    public static Integer parseJsonIdStr(String jsonStr) {
        JSONObject json = JSONObject.parseObject(jsonStr);
        if (null == json) {
            return -1;
        } else {
            Integer id = json.getInteger("id");
            if (null == id) {
                return -1;
            } else {
                return id;
            }
        }
    }

    public static List<Integer> parseJsonIdsStr(String jsonStr) {
        List<Integer> result = new ArrayList<>();
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        if (null != jsonArray && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                Integer id = json.getInteger("id");
                if (null != id) {
                    result.add(id);
                }
            }
        }
        return result;
    }

    /**
     * @param json
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @desc json转map
     */
    public static Map<String, Object> jsonToMap(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map;
        try {
            map = (Map<String, Object>) objectMapper.readValue(json, Map.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        }
        return map;
    }


    /**
     * @param json
     * @return java.util.List<java.util.Map < java.lang.String, ?>>
     * @Author AlphaJunS
     * @Date 19:07 2020/3/27
     * @desc json转List<Map < String, ?>>
     */
    public static List<Map<String, ?>> jsonToMapList(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Map.class);
        List<Map<String, ?>> mapList;
        try {
            mapList = (List<Map<String, ?>>) objectMapper.readValue(json, javaType);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        }
        return mapList;
    }

    /**
     * @param map
     * @return java.lang.String
     * @desc map转json
     */
    public static String mapToJson(Map<String, Object> map) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(map);
        return jsonString;
    }

    /**
     * @param object
     * @return java.lang.String
     * @desc 对象转json
     */
    public static String objectToJson(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonList = null;
        try {
            jsonList = objectMapper.writeValueAsString(object);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
        }
        return jsonList;
    }

    /**
     * @param mapList
     * @return java.lang.String
     * @desc List<Map < String, ?>>转json
     */
    public static String mapListToJson(List<Map<String, Object>> mapList) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonList;
        try {
            jsonList = objectMapper.writeValueAsString(mapList);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("Error", e);
            throw e;
        }
        return jsonList;
    }

    /**
     * @param args
     * @return java.lang.String
     * @desc 数组转json
     */
    public static String arrayToJson(String[] args) throws Exception {
        // 先讲数组转化为map，然后map转json
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < args.length; i++) {
            map.put(i + "", args[i]);
        }
        String json = JsonTool.objectToJson(map);
        return json;
    }


    /**
     * 去除json值前后空格
     * @param jsonStr jsonStr
     * @return
     */
    public static JSONObject jsonTrim(String jsonStr) {
        return jsonTrim(JSONObject.parseObject(jsonStr));
    }

    /**
     * 去除value的空格
     *
     * @param jsonObject jsonObject
     * @return
     */
    public static JSONObject jsonTrim(JSONObject jsonObject) {
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            Object value = entry.getValue();
            if (value != null) {
                if (value instanceof String) {
                    //清空值前后空格
                    jsonObject.put(entry.getKey(), ((String) value).trim());
                } else if (value instanceof JSONObject) {
                    jsonTrim((JSONObject) value);
                } else if (value instanceof JSONArray) {
                    jsonTrimArray((JSONArray) value);
                }
            }
        }

        return jsonObject;
    }

    /**
     * 清空JSONArray 值前后空格
     *
     * @param array
     */
    public static JSONArray jsonTrimArray(JSONArray array) {
        if (array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                Object object = array.get(i);
                if (object != null) {
                    if (object instanceof String) {
                        array.set(i, ((String) object).trim());
                    } else if (object instanceof JSONObject) {
                        jsonTrim((JSONObject) object);
                    } else if (object instanceof JSONArray) {
                        jsonTrimArray((JSONArray) object);
                    }
                }
            }
        }

        return array;
    }

}
